package cn.hp.controller;

import cn.hp.entity.Menu;
import cn.hp.service.MenuService;
import cn.hp.util.util.Result;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/menu")
public class MenuController {
    @Autowired
    private MenuService menuService;

     @GetMapping("/getMenu")
    public Result getMenu(Menu menu) {
        List<Menu> list = menuService.selectMenu(menu);
        List<Map<String, Object>> mmenu = new ArrayList<>(); // 空的
        for (Menu menu1 : list) {
            if (menu1.getMenuType().equals("M")) {
                Map<String, Object> map = new HashMap<>();
                map.put("id", menu1.getMenuId());
                map.put("title", menu1.getMenuName());
                List<Map<String, Object>> childList = new ArrayList<>();
                for (Menu menu2 : list) {
                    if (menu2.getMenuType().equals("C") && (menu1.getMenuId() -
                            menu2.getParentId() == 0)) {
                        Map<String, Object> childMap = new HashMap<>();
                        childMap.put("id", menu2.getMenuId());
                        childMap.put("title", menu2.getMenuName());
                        childList.add(childMap);
                    }
                }
                map.put("children", childList);
                mmenu.add(map);

            }
        }
        return Result.success(mmenu);
    }

    @GetMapping
    public Result find(Menu menu) {
        List<Menu> list = menuService.selectMenu(menu);
        return Result.success(list);
    }

    @RequestMapping("/page")
    public Result page(Menu menu, @RequestParam(value = "page", defaultValue =
            "1") Integer page, @RequestParam(value = "limit", defaultValue = "10") Integer
                               limit) {
        PageInfo<Menu> menuList = menuService.selectMenu(menu, page, limit);
        return Result.success(menuList);
    }

    @PostMapping
    public Result add(@RequestBody Menu menu) {
        int i = menuService.insertMenu(menu);
        return i > 0 ? Result.success("添加失败") : Result.error("添加失败");
    }

    @PutMapping
    public Result update(@RequestBody Menu menu) {
        int i = menuService.updateMenu(menu);
        return i > 0 ? Result.success("修改成功") : Result.error("修改失败");
    }

    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id) {
        int i = menuService.deleteMenuById(id);
        return i > 0 ? Result.success("删除成功") : Result.error("删除失败");
    }


}
